package com.ee.chat.api.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/ws/{uid}")
public class WebSocketServer {
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);

    //concurrent包的线程安全Set，用来存放每个客户端对应的webSocket对象
    private static ConcurrentHashMap<Integer, Session> sessionMap = new ConcurrentHashMap<>();

    @Resource
    RedisMessageListenerContainer redisMessageListenerContainer;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("uid") Integer uid) {
        sessionMap.put(uid, session);

//        log.info("连接成功，当前id为："+uid);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("uid") Integer uid) {
        sessionMap.remove(uid);

//        log.info("有连接关闭，当前id为："+uid);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     *    客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("uid") Integer uid) {
//        log.info("来自客户端的消息，当前id为："+uid+"，消息为：", message);
//        SendMessage(session, "收到消息，消息内容："+message);
    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        /*for(Map.Entry<Integer, Session> entry : sessionMap.entrySet()){
            if(session == entry.getValue()){
                Integer uid = entry.getKey();

                log.error("发生错误：{}，用户id："+uid, error.getMessage(), session.getId());
                return;
            }
        }*/
//        log.error("发生错误：{}，Session ID： {}", error.getMessage(), session.getId());
//        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param uid
     * @param message
     */
    public void sendMessage(@PathParam("uid") Integer uid, String message) {
        try {
            Session session = sessionMap.get(uid);
            if(session != null && session.isOpen()){
//                log.debug(uid+"发送消息："+message);

                session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     * @param message
     * @throws IOException
     */
    public void broadcastSendMeaages(String message) throws IOException {
        for(Map.Entry<Integer, Session> entry : sessionMap.entrySet()){
            sendMessage(entry.getKey(), message);
        }
    }



}
